-- Autocmds are automatically loaded on the VeryLazy event
-- Default autocmds that are always set: https://github.com/LazyVim/LazyVim/blob/main/lua/lazyvim/config/autocmds.lua
-- Add any additional autocmds here

-- added for ts auto cleanup
-- vim.api.nvim_create_autocmd("BufWritePre", {
--   group = augroup("organise_imports"),
--   pattern = "*.ts",
--   callback = function()
--     vim.lsp.buf.code_action({ apply = true, context = { only = { "source.addMissingImports.ts" }, diagnostics = {} } })
--     vim.lsp.buf.code_action({ apply = true, context = { only = { "source.removeUnused.ts" }, diagnostics = {} } })
--   end,
-- })

vim.api.nvim_create_autocmd("VimLeave", {
  command = 'set guicursor= | call chansend(v:stderr, "\x1b[ q")',
})

-- fix file type detection for .cds files
vim.api.nvim_create_autocmd({ "BufRead", "BufEnter" }, {
  pattern = { "*.cds" },
  callback = function()
    vim.bo.filetype = "cds"
  end,
})

-- Disable vtsls formatting when eslint is present
local lsp_conflicts, _ = pcall(vim.api.nvim_get_autocmds, { group = "LspAttach_conflicts" })
if not lsp_conflicts then
  vim.api.nvim_create_augroup("LspAttach_conflicts", {})
end

local function resolveDenoLsConflicts()
  local is_deno = require("lspconfig.util").root_pattern("deno.json", "deno.jsonc")
  -- Disable typescript-tools if in a deno workspace
  if LazyVim.lsp.is_enabled("denols") and LazyVim.lsp.is_enabled("typescript-tools") then
    LazyVim.lsp.disable("typescript-tools", is_deno)
    LazyVim.lsp.disable("denols", function(root_dir, config)
      if not is_deno(root_dir) then
        config.settings.deno.enable = false
      end
      return false
    end)
  end
  -- Disable tsserver if in a deno workspace
  if LazyVim.lsp.is_enabled("denols") and LazyVim.lsp.is_enabled("tsserver") then
    LazyVim.lsp.disable("tsserver", is_deno)
    LazyVim.lsp.disable("denols", function(root_dir, config)
      if not is_deno(root_dir) then
        config.settings.deno.enable = false
      end
      return false
    end)
  end
end

local function resolveTSFormatters(client, active_clients)
  -- Check if the attached client is eslint or tsserver
  if client.name == "eslint" then
    for _, client_ in pairs(active_clients) do
      -- Disable vtsls formatting if eslint is active to avoid conflicts
      if client_.name == "vtsls" then
        client_.server_capabilities.documentFormattingProvider = false
        client_.server_capabilities.documentRangeFormattingProvider = false
      end
      -- Disable vtsls formatting if eslint is active to avoid conflicts
      if client_.name == "typescript-tools" then
        client_.server_capabilities.documentFormattingProvider = false
        client_.server_capabilities.documentRangeFormattingProvider = false
      end
    end
  elseif client.name == "vtsls" then
    for _, client_ in pairs(active_clients) do
      -- Disable vtsls formatting if eslint or prettier is already attached
      if client_.name == "eslint" or client_.name == "prettier" then
        client.server_capabilities.documentFormattingProvider = false
        client_.server_capabilities.documentRangeFormattingProvider = false
      end
    end
  elseif client.name == "typescript-tools" then
    for _, client_ in pairs(active_clients) do
      -- Disable vtsls formatting if eslint or prettier is already attached
      if client_.name == "eslint" or client_.name == "prettier" then
        client.server_capabilities.documentFormattingProvider = false
        client_.server_capabilities.documentRangeFormattingProvider = false
        return -- Early return to avoid multiple prints
      end
    end
  end
end

vim.api.nvim_create_autocmd("LspAttach", {
  group = "LspAttach_conflicts",
  desc = "Prevent typescript-tools competing for formatting with other formatters",

  callback = function(args)
    if not (args.data and args.data.client_id) then
      return
    end

    local client = vim.lsp.get_client_by_id(args.data.client_id)
    if client == nil then
      return
    end

    local active_clients = vim.lsp.get_clients({ bufnr = args.buf })
    resolveTSFormatters(client, active_clients)

    resolveDenoLsConflicts()
  end,
})
